package com.redpacketcover.rc.base;

import android.annotation.SuppressLint;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.redpacketcover.rc.Constants;
import com.redpacketcover.rc.util.AppUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitManager {
    private final static int CONNECT_TIMEOUT = 30;
    private final static int READ_TIMEOUT = 100;
    private final static int WRITE_TIMEOUT = 100;
    private Retrofit mRetrofit;
    private static RetrofitManager mManager;
    // Log信息拦截器
    private static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.i("HTTPLOG", message);

        }
    });

    // 添加公共请求参数
    String appVersion = AppUtils.INSTANCE.getAppVersionName();
    CommonInterceptor commonInterceptor = new CommonInterceptor.Builder()
            .addParams("device", "android") //安卓系统
            .addParams("appversion", appVersion.replace(".", "")) //版本号
            .build();


    public RetrofitManager() {
        if (mRetrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.addInterceptor(new AddHeaderInterceptor());
            builder.addInterceptor(commonInterceptor);
            builder.addInterceptor(loggingInterceptor); //设置 Debug Log 模式
            builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//连接超时时间
            builder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);//写操作 超时时间
            builder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);//读操作超时时间
            builder.sslSocketFactory(createSSLSocketFactory());

            // 创建Retrofit
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(Constants.URL_HOST_TEST)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(builder.build())
                    .build();
        }

    }


    /**
     * 获取RetrofitManager
     */
    public static RetrofitManager getInstance() {
        if (mManager == null) {
            synchronized (RetrofitManager.class) {
                if (mManager == null) {
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    mManager = new RetrofitManager();
                }
            }
        }
        return mManager;
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service) {
        return mRetrofit.create(service);
    }


    @SuppressLint("TrulyRandom")
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()}, new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return sSLSocketFactory;
    }

}
